import { View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import NavBar from "@/components/menus/NavBar";
import { Cross, Arrow } from "@taroify/icons";
import { RenderInfoBetween } from "@/utils/render";
import { getUser } from "@/utils/auth";
import { SectorType, UserType } from "@/types";
import { CreateBarMenuType } from "@/types/menu";
import { useState } from "react";
import { Popup, Button, FloatingPanel, Checkbox } from "@taroify/core";
import TreeSelect from "@/components/common/TreeSelect";
import SelectAvatar from "@/components/user/SelectAvatar";
import { createSectorApi } from "@/api";
import { toast } from "@/utils";
import upload from "@/api/upload";

export default () => {
  const user: UserType = getUser();
  const [sector, setSector] = useState<SectorType>();
  const [avatar, setAvatar] = useState("");
  const [checked, setChecked] = useState(false);
  const change = (key, value) => {
    console.log(key, value);
    setSector((prev) => ({
      ...prev,
      [key]: value, // 更新对应的 sector 属性
    }));
  };

  const menus: Array<CreateBarMenuType> = [
    {
      group: "个人信息",
      items: [
        { title: "创建人", right: user.username, type: "node" },
        {
          title: "手机号",
          right: (
            <View className="flex items-center">
              {user.phone}
              <Button size="mini" variant="text" color="info">
                修改
              </Button>
            </View>
          ),
          type: "node",
        },
        { title: "邮箱地址", right: user.email, type: "node" },
      ],
    },
    {
      group: "建吧信息",
      items: [
        {
          title: "版块名",
          type: "input",
          k: "sectorName",
          change,
          placeholder: "最多12个字",
        },
        {
          title: "版块标签",
          k: "sectorTagId",
          right: <SelectTag change={(e) => change("sectorTagId", e)} />,
          type: "node",
        },
        {
          title: "版块头像",
          k: "sectorUrl",
          right: (
            <View className="flex justify-center items-center gap-1">
              <SelectAvatar change={setAvatar} />
              <Arrow />
            </View>
          ),
          type: "node",
        },
        {
          title: "版块简介",
          type: "textarea",
          k: "sectorSynopsis",
          change,
          placeholder: "输入板块简介",
        },
        {
          title: "版块规则",
          type: "textarea",
          k: "sectorRule",
          change,
          placeholder: "该板块需要遵守的规则",
        },
      ],
    },
  ];

  async function createSector() {
    console.log(sector);
    if (!checked) return toast("请先阅读《建吧流程》");
    if (!sector?.sectorName) return toast("请输入板块名称");
    if (!sector?.sectorTagId) return toast("请选择板块标签");
    if (!avatar) return toast("请先选择板块头像");
    if (!sector?.sectorSynopsis) return toast("请输入板块简介");
    if (!sector?.sectorRule) return toast("请输入板块规则");
    const img = await upload(avatar);
    const params = {
      ...sector,
      sectorUrl: img,
      userId: user.kid,
    };
    createSectorApi(params).then(() =>
      setTimeout(() => Taro.navigateBack(), 2000)
    );
  }

  return (
    <NavBar
      title=" "
      left={<Cross onClick={() => Taro.navigateBack()} size={24} />}
    >
      <View className="relative text-2xl font-bold text-center">
        创建你喜欢的板块吧
      </View>
      <View className="p-4 pb-32">
        {menus.map((item) => {
          return (
            <View key={item.group} className="bg-white rounded-lg my-3 p-3 ">
              <View className=" font-medium mb-4">{item.group}</View>
              <View className="px-1">
                {item.items.map((el, i) => {
                  return (
                    <RenderInfoBetween
                      key={i}
                      k={el.k}
                      title={el.title}
                      type={el.type}
                      right={el.right}
                      placeholder={el.placeholder}
                      change={el.change}
                      textDirection="right"
                    />
                  );
                })}
              </View>
            </View>
          );
        })}
      </View>
      <FloatingPanel anchors={[120]}>
        <View className="flex justify-center items-center flex-col gap-2 px-4">
          <Button
            size="small"
            shape="round"
            className="w-full "
            color="primary"
            onClick={createSector}
          >
            创建板块
          </Button>
          <Checkbox size={12} checked={checked} onChange={setChecked}>
            <View className="text-xs text-[#B0B0B0]">
              我已阅读并同意《建吧流程》
            </View>
          </Checkbox>
        </View>
      </FloatingPanel>
    </NavBar>
  );
};

function SelectTag({ change }) {
  const [value, setValue] = useState("");
  const [open, setOpen] = useState(false);
  function select(e) {
    setValue(e);
    setOpen(false);
    change && change(e);
  }
  return (
    <View>
      <View onClick={() => setOpen(true)}>
        {value || "请选择标签"} <Arrow />
      </View>
      <Popup
        lock
        rounded
        open={open}
        placement="bottom"
        onClose={() => setOpen(false)} // 添加 onClose 处理
        style={{ height: "70%" }}
      >
        <TreeSelect value={value} onChange={select} />
        <Popup.Close />
      </Popup>
    </View>
  );
}
